package org.parademo.web.controller;

import org.parademo.model.TopicEntity;
import org.parademo.service.TopicService;
import org.parademo.web.model.TopicView;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("/topic")
public class
        TopicController {
    private final TopicService topicService;

    public TopicController(TopicService topicService) {
        this.topicService = topicService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String showTopicForm(@ModelAttribute("topic") TopicView topic,
                                Model model) {

        List<TopicEntity> topics = topicService.getTopics();
        model.addAttribute("topics",topics);

        return "topic";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String newTopic(@ModelAttribute("topic") TopicView topic,
                           BindingResult bindingResult,
                           Model model) {

        List<TopicEntity> topics = topicService.getTopics();
        model.addAttribute("topics",topics);

        topic.validateUsing(bindingResult);
        if (bindingResult.hasErrors()) {
            return "topic";
        }

        topicService.createTopic(topic);

        return "redirect:/topic";
    }
}
